#include "modbus-service.h"
#include <stdio.h>
#include "usart.h"
#include "ticker.h"
#include "modbus-crc.h"

void Modbus_Init(void)
{
	Usart1_Init();
	Usart1_Interrupt(1);
}
void Modbus_Loop(void)
{
	unsigned short crc = 0;
	unsigned long b = 0, e = 0;
	int len = RingBuffer_Length(usart1_buffer);
	unsigned char data[8] = {1, 3, 0, 0, 0, 1, 0, 0};
	
	if( len >= sizeof(data) && Usart1_Diff() > 3 )
	{
		Usart1_Interrupt(0);
		
		printf("\r\n%lu,%d{%d,%d}-", Usart1_FDiff(), len, usart1_buffer.beg, usart1_buffer.end);
		b = Ticker_Get();
		RingBuffer_GetData(usart1_buffer, data, sizeof(data));
		crc = CRC16(data, sizeof(data));
		while(Ticker_Get()-b == 0);
		e = Ticker_Get();
		printf("{%d,%d}, ", usart1_buffer.beg, usart1_buffer.end);
		printf("crc=%04X, diff=%lu ", crc, e - b);

		Usart1_Interrupt(1);
	}
}
